package chess.model;

import java.net.SocketException;

import chess.server.ServerConnection;

public class Session {

	private static Session INSTANCE;

	private ServerConnection connection;

	private ConnectionDetails connectionDetails;

	private boolean connected = false;

	private boolean offline = true;

	public boolean isOffline() {
		return offline;
	}

	public void setOffline(boolean offline) {
		this.offline = offline;
	}

	public boolean isConnected() {
		return connected;
	}

	private Session() {
		// enforce the singleton patter
	}

	public ConnectionDetails getConnectionDetails() {
		return connectionDetails;
	}

	public void setConnectionDetails(ConnectionDetails connectionDetails) {
		this.connectionDetails = connectionDetails;
	}

	public ServerConnection getConnection() {
		return connection;
	}

	public void setConnection(ServerConnection connection) {
		this.connection = connection;
	}

	public static Session getInstance() {
		if (INSTANCE == null)
			INSTANCE = new Session();
		return INSTANCE;
	}

	public void connectAndLogin() {
		connection = new ServerConnection(connectionDetails.getServer(), 5000);
		try {
			if (!connectionDetails.getServer().equals("")) {
				connection.connect();
				setConnection(connection);
				connection.login(connectionDetails.getUserId(),
						connectionDetails.getPassword());
				offline = false;
			}
			System.out.println("Conected TRUE");
			connected = true;
//			connection.setAuthenticated(true);
			
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			System.out.println("dsadsadsa");
			e.printStackTrace();

		}

		// throws XMPPException {
		// PacketListener progressPacketListener = new PacketListener() {
		// public void processPacket(Packet packet) {
		// if (monitor.isCanceled())
		// throw new OperationCanceledException();
		// String message = null;
		// // if (packet instanceof Authentication)
		// // message = "Authenticating...";
		// // if (packet instanceof RosterPacket)
		// // message = "Receiving roster...";
		// if (message != null)
		// monitor.subTask(message);
		// }
		// };
		// // try {
		// monitor.beginTask("Connecting...", IProgressMonitor.UNKNOWN);
		// monitor.subTask("Contacting " + connectionDetails.getServer()+
		// "...");
		// connection = new ServerConnection(connectionDetails.getServer(),
		// 5222);
		// connection.addPacketWriterListener(progressPacketListener);
		//
		// connection.login(connectionDetails.getUserId(), connectionDetails
		// .getPassword());
		// // connection.getRoster().setSubscriptionMode(
		// // Roster.SUBSCRIPTION_ACCEPT_ALL);
		// // } finally {
		// if (connection != null)
		// connection.removePacketWriterListener(progressPacketListener);
		// monitor.done();
		// }
	}

}
